import 'package:flutter/material.dart';
import 'package:dio/dio.dart';

import '../services/ScreenAdapter.dart';
import '../widget/MyText.dart';
import '../widget/MyButton.dart';
import '../services/UserInfo.dart';
import '../config/Config.dart';
import '../services/EventBus.dart';

// 消息弹框
import 'package:fluttertoast/fluttertoast.dart';

class LoginPage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => LoginPageState();
}

class LoginPageState extends State {
  String username='';
  String password='';

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          leading: IconButton(
            icon: Icon(Icons.close),
            onPressed: () {
              Navigator.pop(context);
            },
          ),
          actions: [
            FlatButton(
              child: Text('客服'),
              onPressed: () {},
            ),
          ],
        ),
        body: ListView(
          children: [
            Container(
              margin: EdgeInsets.only(top: 30),
              width: ScreenAdapter.width(160),
              height: ScreenAdapter.height(160),
              child: Image.asset('images/login.png', fit: BoxFit.contain),
            ),
            MyText(
                text: '用户名/手机号',
                onChange: (value) {
                  this.setState(() {
                    this.username = value;
                  });
                }),
            MyText(
                text: '请输入密码',
                obscureText: true,
                onChange: (value) {
                  this.setState(() {
                    this.password = value;
                  });
                }),
            Container(
              margin: EdgeInsets.all(20),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Text('忘记密码', style: TextStyle(color: Colors.black54)),
                  InkWell(
                    child:
                        Text('新用户注册', style: TextStyle(color: Colors.black54)),
                    onTap: () {
                      Navigator.pushNamed(context, '/registerFirst');
                    },
                  ),
                ],
              ),
            ),
            SizedBox(height: 20),


            MyButton(
              text: '登录',
              rightMargin: 50,
              leftMargin: 50,
              color: Colors.red,
              height: 80,
              cb: _login,
            )
          ],
        ));
  }

  //  登录
  _login() async {
    RegExp reg = new RegExp(r'^1\d{10}$');

    // 判断用户名或手机是否符合规则
    if (!reg.hasMatch(this.username)){
      // 弹框提示
      Fluttertoast.showToast(
        msg: "用户名或手机号格式不正确",
        toastLength: Toast.LENGTH_SHORT,
        gravity: ToastGravity.CENTER,
      );
    }else if(this.password.length < 6){
      // 弹框提示
      Fluttertoast.showToast(
        msg: "秘密必须大于6位",
        toastLength: Toast.LENGTH_SHORT,
        gravity: ToastGravity.CENTER,
      );
    }else{
      var api = Config.domain + 'api/doLogin';
      var response = await Dio().post(api, data: {
        "username": this.username,
        "password": this.password,
      });
      var res = response.data;
      print(res);
      if(res['success']){
        // 将登录信息保存到内存中
        UserInfoServices.setUserInfo(res['userinfo']);
        // 通过eventBus广播，通知上一个页面user页面刷新
        eventBus.fire(new UserUploadEvent('user页面刷新'));
        // 返回前一页
        Navigator.pop(context);
      }else {
        // 弹框提示
        Fluttertoast.showToast(
          msg: "${res['message']}",
          toastLength: Toast.LENGTH_SHORT,
          gravity: ToastGravity.CENTER,
        );
      }
    }


  }
}
